package com.example.manage_dzensaas.service;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.manage_dzensaas.core.utils.DateUtils;
import com.example.manage_dzensaas.mapper.db2.AgentSalesDetailRestrictionMapper;
import com.example.manage_dzensaas.mapper.db2.SiteCardSetMapper;
import com.example.manage_dzensaas.pojo.bo.card.QueryCardBo;
import com.example.manage_dzensaas.pojo.entity.db2.SiteCardSet;
import com.example.manage_dzensaas.pojo.result.ApiResult;
import com.example.manage_dzensaas.pojo.vo.CardInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.solon.annotation.Db;
import org.noear.solon.annotation.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author wangzhiqi
 * @version 1.0
 * @description: 卡卷服务类
 * @date 2025/2/12 15:06
 */
@Component
public class CardInvokeService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CardInvokeService.class);

    @Db("db2")
    SiteCardSetMapper siteCardSetMapper;
    @Db("db2")
    AgentSalesDetailRestrictionMapper agentSalesDetailsRestrictionMapper;

    public ApiResult<CardInfoVo> listByCard(QueryCardBo queryCardBo) {
        LOGGER.info("根据卡卷兑换码查询卡卷入参：{}", JSON.toJSONString(queryCardBo));
        SiteCardSet cardSet = siteCardSetMapper.selectOne(new QueryWrapper<SiteCardSet>()
                .select("id", "card_id", "card_number", "face_value", "validity_end_time", "is_use", "status")
                .eq("exchange_code", queryCardBo.getExchangeCode()).last("limit 1"));

        if (cardSet == null) {
            return ApiResult.error("卡密不存在");
        } else if (cardSet.getIsUse().equals(1)) {
            return ApiResult.error("卡密已绑定");
        } else if (cardSet.getStatus().equals(0)) {
            return ApiResult.error("卡密未激活，请联系商城客服");
        } else if (cardSet.getValidityEndTime().getTime() < System.currentTimeMillis()) {
            return ApiResult.error("卡密已过期，请联系商城客服");
        } else if (cardSet.getFaceValue() == null) {
            return ApiResult.error("卡密金额面值错误");
        }

        CardInfoVo cardInfoVo = new CardInfoVo();
        if (cardSet.getSalesOrderId() != null) {
            String cardName = siteCardSetMapper.getByCardName(cardSet.getSalesOrderId(), cardSet.getCardId());
            if (StringUtils.isNotEmpty(cardName)) {
                cardInfoVo.setCardName(cardName);
            }
        }
        cardInfoVo.setId(cardSet.getId());
        cardInfoVo.setCardId(cardSet.getCardId());
        cardInfoVo.setCardNumber(cardSet.getCardNumber());
        cardInfoVo.setFaceValue(cardSet.getFaceValue());
        cardInfoVo.setCardType(cardSet.getCardType());
        cardInfoVo.setValidityEndTime(DateUtils.dateToString(cardSet.getValidityEndTime(), DateUtils.DATE));
        return ApiResult.success(cardInfoVo);
    }
}
